'; window.popUpWin.document.write(zhtm); window.popUpWin.document.close(); // Johnny Jackson 4/28/98 } //--> Inside AutoCAD 14 -- Ch 25 -- ActiveX Automation


Inside AutoCAD 14

Previous chapterNext chapterContents


- 25 -

ActiveX Automation


by Surya Sarda

ActiveX Automation is a new feature in AutoCAD Release 14. Using this feature, you can customize AutoCAD and create powerful custom applications by combining AutoCAD objects with objects available from other applications that support ActiveX Automation. With ActiveX Automation, you can develop macros and custom applications by using modern, standard, user-friendly languages such as Visual Basic 5.0. These tools enable you to automate repetitive tasks (such as parameterized part creation). Using ActiveX Automation, you can automatically generate a bill of materials from an AutoCAD drawing file, create an Excel spreadsheet, build a chart, put the chart in a Microsoft Word memo, or mail or fax it--all in one relatively simple application using objects that the different applications expose.

You can create and manipulate AutoCAD objects from any application that serves as an ActiveX Automation controller. Besides Visual Basic 5.0, some of the other popular Automation controllers are Microsoft Visual C++ and Delphi. AutoCAD Automation works with the popular Automation controllers Visual Basic 5.0 and Microsoft Visual C++, but does not work with Delphi.

For simplicity, this chapter refers to AutoCAD ActiveX Automation as Automation. As you read this chapter and use Automation, some previous understanding of Visual Basic or programming would be helpful. This chapter covers the following topics:

Introducing ActiveX Automation

ActiveX Automation (previously called OLE Automation) is a technology developed by Microsoft. AutoCAD ActiveX Automation features provide a modern alternative to AutoLISP, although AutoLISP has a rich set of features and Automation is not intended to replace it. The most popular Automation controller is Visual Basic. Because the exposed objects are accessible from any macro language or tool that can access Automation objects, you can choose a tool based on your current knowledge (rather than learn a new language, such as AutoLISP, for each application).

Programming in Visual Basic is relatively easy. After you learn to program one application in Visual Basic, you can build on this knowledge to program any other application. Visual Basic provides standard functions (such as the math and string-manipulation functions). You have to learn only the AutoCAD-specific functions, and thus can focus on the functionality of your application rather than on the intricacies of the specific macro language. The Automation interface for AutoCAD resembles the Automation interface for Excel and Access. If you already know Excel or Access macro programming, learning AutoCAD Automation programming will be easy.

Visual Basic provides a user-friendly environment for creating a Graphical User Interface (GUI) or front end for your programs. Instead of using AutoCAD Dialog Control Language, you can use Visual Basic to develop the entire user interface. You cannot, however, use Visual Basic to replace AutoCAD dialog boxes or to add new dialog boxes in AutoCAD.

In addition to the languages mentioned earlier (VB and C++), you can use Microsoft Visual Basic for Applications (VBA) as an Automation controller. Microsoft Office 97 components include VBA. As this chapter is being written, more than 50 VBA licenses exist. This number will continue to grow as more and more applications adopt VBA. AutoCAD Release 14 includes a preview version of the program. AutoCAD's VBA is identical to the one in Office 97--except for one major difference: AutoCAD VBA is embedded in AutoCAD and runs in-process. This feature helps improve the performance of your applications substantially when they interact with AutoCAD objects. The other advantage of using AutoCAD VBA is that you can use the Automation feature without purchasing full-featured Visual Basic software.

Now that you know what Automation is used for, it is important to cover some of the basic Automation-related terms and definitions that appear throughout the chapter.

Terms and Definitions

You need to become familiar with a few terms before you begin to program. This section attempts to explain the terms in simple language.

An Automation controller is the application that controls the server application. For example, AutoCAD is used as a server application with VBA or Visual Basic operating as the Automation controller. The controller initiates the interaction with the server, and server applications respond to the commands issued by the controller application.

An AutoCAD object is an element of AutoCAD. Line, UserCoordinateSystem, and Layer are examples of AutoCAD objects. Each AutoCAD object has a set of methods and properties (functions that set or return information about an object), and only the predefined set of functions can be used to program a particular object.

A property represents an attribute of an object, and can be read-only or read-write. A program can assign a new value to the read-write properties, but the program can only access the value of the read-only properties.

Methods are functions (such as Move, Copy, Regen, and Save) that perform an action on an object. A method might or might not return a value. Methods can take any number of arguments, any of which can be optional. Arguments are passed by value or by reference.

The AutoCAD object model represents the available AutoCAD objects and their interrelationships. The diagrams shown in figures 25.1 and 25.2 provide an overview of the hierarchical relationship between various objects exposed in AutoCAD.

Figure 25.1 AutoCAD Object Model shows the hierarchical relationship between various objects.

Figure 25.2 AutoCAD Object Model (Part II) shows the hierarchical relationship between various objects.

AutoCAD exposes many objects. Luckily, there are tools available that assist you in finding out what each object does and how it can be coded. Next, you will take a look at these tools.


NOTE: The first example in this chapter uses Visual Basic 5.0. You can also use the AutoCAD Release 14 Visual Basic for Applications (VBA) as the development environment.

Using the Object Browser and Online Help

Automation objects can be viewed through an Object Browser that comes with Visual Basic or VBA. The Object Browser enables you to see the complete list of objects available in an application, along with the properties and methods applicable to each object. You can also access online help and a code sample on how to use each particular method or property.

Before you can use AutoCAD's Automation objects, you must reference AutoCAD's type library (see fig. 25.3).

To reference the AutoCAD object type library, follow these steps:

1. From the Project menu, choose References.

2. In the References dialog box, select AutoCAD Object Library or, if it's not listed, choose Browse and select the acad.tlb file in the AutoCAD executable directory.

Figure 25.3 The Object Browser in Visual Basic 5.0 lists the AutoCAD Objects and corresponding methods and properties for each object.

The Browser has undergone significant changes in Visual Basic 5.0. The new Browser in Visual Basic 5.0 resembles the VBA Object Browser (see fig. 25.4).

Figure 25.4 Significant changes are evident in the Object Browser in Visual Basic 5.0.

The Object Browser is part of the Visual Basic Editor, also known as VBA Integrated Development Environment (IDE) (see fig. 25.5). You use the editor and the tools provided to design the layout of your application, write Visual Basic code, and debug your application. The editor in Visual Basic 5.0 is nearly identical to that in VBA. You can bring up the editor after installing AutoCAD VBA by clicking on the Show IDE item under the VBA menu in AutoCAD. The advantage of VBA is that after you learn about this environment once, you can use it easily with any applications that support VBA.

To display the Object Browser in AutoCAD VBA, choose Object Browser under the View menu of the Visual Basic Editor. As you can see in figures 25.3-25.5, the Object Browser's left column contains the list of objects for the selected application; the properties and methods associated with the highlighted object are displayed in the right column. The Object Browser connects you directly to the online help for Automation. Coding examples for each method and property are included in the help page of the help file. You can use the coding examples to learn more about a particular method or property. You can also use the Object Browser to determine whether a property applies to a particular object.

Figure 25.5 The Visual Basic for Applications (VBA) Editor.

Looking Up Online Help Through the Object Browser

To get to online help for a particular method or property of an object, first highlight the object in the left column, then highlight the item in the right column, and then click on the question mark button. The following exercise shows you how to look up the online help and code sample for Rotate method of BlockReference object. The exercise assumes you have loaded AutoCAD VBA. Confirm this by starting an AutoCAD session and verifying the existence of the VBA pull-down menu.

USING ONLINE HELP

1. Open the VBA pull-down menu and choose the Show VBA IDE command. This will start AutoCAD VBA (Microsoft Visual Basic).

2. Open the View pull-down menu and choose Object Browser. A Classes List and a Members list should now fill the left window on the screen.

3. Scroll down the left column (Classes) and pick the BlockReference object by clicking on IAcadBlockReference.

4. In the right column (Members of `IAcadBlockReference' list), pick the Rotate method.

5. With these items highlighted, click on the question mark button. Do not select the question mark icon on the Standard toolbar--this brings up help topics for Visual Basic for Applications.

6. The help information for the object is displayed.

7. Click on the green Example hotspot to see a code sample (see fig. 25.6).

8. From the AutoCAD Automation Reference dialog box, open the File pull-down menu, and choose Exit to leave the help screen. From the Microsoft Visual Basic dialog box, open the File pull-down menu and choose the Close and Return to AutoCAD command.

Figure 25.6 The Help page for the Rotate method of the BlockReference object.

The Object Browser provides a quick method of looking up online help and code samples on how to use a particular method or property in AutoCAD. Becoming familiar with the Object Browser will make creating Automation programs easier and more efficient.

Creating Your First Automation Program

In this section, you learn to write your first simple Automation program. In the following exercise, you will gain insight into how easy it is to write a Visual Basic program. The only way to learn programming is to write programs. Writing a Visual Basic program entails two major tasks: designing the graphical layout and writing the code.

During the graphical layout step, which does not involve any coding, you use the tools that come with Visual Basic to lay out the user interface for the application. In this step, you can use your imagination to make your application visually appealing.

In the second step, you write the code, using Visual Basic statements. Writing code in Visual Basic is easier than other languages because it is more like English.

AUTOMATION ROUTINE--START AND END AN AUTOCAD SESSION


In this simple exercise, you create the user interface to start and end an AutoCAD session. Then you write the code behind the user interface, and run the exercise to see how Visual Basic can be used to link to AutoCAD. Figure 25.7 shows the finished form you are going to create.

Figure 25.7 The Visual Basic Form for Exercise 1.


To create this form, follow these steps: 1. Start Visual Basic 5.0.

The Visual Basic Editor with the default form is displayed. To create the look of your application (the way it appears to the user), you will place various buttons from the toolbox on this form.

2. If the Toolbox and Properties dialog boxes are not displayed, open the View pull-down menu and choose the Toolbox and Properties commands.

3. Double-click on the command icon in the toolbox. A button with the caption Command1 appears (see fig. 25.8). Place the cursor over the control button and press and hold down the left mouse button. Drag the control to the upper-left corner of the form.

Figure 25.8 The Visual Basic Form with the first button.

4. Double-click on the command icon to place a second command button. Place the cursor over the control button and press and hold down the left mouse button. Drag the control below the first command button.

5. Double-click on the check box button to place a check box in the center of the form. Place the cursor over the check box button and press and hold down the left mouse button. Drag the control to the right of the two command buttons.

6. Make changes to the property page for each control by highlighting each control and then editing its properties in the Properties window.


NOTE: To change a property, double-click on the property name. This selects the property and highlights its current value. Type a new value for the property.

7. Select Form1 by picking on any open spot on the form. Set the following properties in the Properties window:

Caption: Exercise 1

Scalemode: 2-Point

8. Select the CommandButton1 on the form, and set the following properties in the Properties window:

Height: 24

Left: 12

Top: 12

Width: 66

Caption: Start AutoCAD

Name: cmdStart

9. Select CommandButton2 on the form, and set the following properties in the Properties window:

Enabled: False

Height: 24

Left: 12

Top: 54

Width: 66

Caption: Quit

Name: cmdQuit

10. Select CheckBox1 on the form, and set the following properties in the Properties window:

Height: 24

Left: 114

Top: 30

Width: 50

Caption: Visible

Name: cmdVisible


At this point, the form should resemble the one shown in figure 25.7.

11. Now, double-click on the Start AutoCAD button and add the following code between the Private Sub and End Sub lines in the code window:

On Error Resume Next
Set acad = GetObject(, "AutoCAD.Application")
              If Err Then
                       Err.Clear
                       Set acad =                         ¬CreateObject("AutoCAD.Application")
                       If Err Then
                           MsgBox "Unable to connect to AutoCAD"
                      Exit Sub
                       End If
End If
cmdQuit.Enabled = True

12. Open the View pull-down menu and choose Form to switch to the form. Double-click on the Quit button, and add the following code between the Private Sub and End Sub lines in the code window:

acad.Quit
End

13. Open the View pull-down menu and choose Form to switch to the form. Double-click on the Visible check box, and add the following code between the Private Sub and End Sub lines in the code window:

acad.Visible = True

14. In the Form1 code window, use the Object drop-down list and select (General). The Proc drop-down list will now show (declarations) and the code window will be empty. Type the following line in the code window:

Public acad As Object

15. Now, open the Run pull-down menu and choose Start With Full Compile to run the example.

The statement Public acad As Object declares the acad variable as public, so that you can access it from any subroutine. The GetObject function connects your application to AutoCAD, if AutoCAD is already running. This function returns the AutoCAD Application object and stores it in the acad variable. CreateObject starts a new session of AutoCAD. AutoCAD stays "invisible" until the "visible" property is set to True. The statement acad.Quit ends the AutoCAD session. To end the application without quitting AutoCAD, just set acad = Nothing. It's a good idea to free up memory associated with objects that will not be used any more; to do so, set those objects to Nothing.


TIP: Sometimes, you might want to run AutoCAD in invisible mode. In this way, you can do several operations with only a final display, without having to regenerate the drawing window after each operation. Also, if you are doing a batch-plot sort of operation, you can make your application run faster if AutoCAD is invisible.

The Application object used in the preceding exercise is the top-level object; all the other objects can be reached through the methods and properties of the Application object. To create an AutoCAD block, for example, you must know how the block object relates to the AutoCAD Application object. Now, take a look at the Object Model to understand how the various objects are connected.

Looking at the AutoCAD Object Model

The following exercise shows you how to look at the AutoCAD Object Model, which shows the relationship between the different AutoCAD objects.

LOOKING AT THE AUTOCAD OBJECT MODEL

1. Access the AutoCAD Release 14 online help system by opening the Help pull-down menu and choosing the AutoCAD Help Topics command. This displays the Help Topics:AutoCAD Help dialog box. Select the Contents tab.

2. Double-click on ActiveX Automation, and then double-click on ActiveX Automation Reference.

3. Double-click on Object Model. This hierarchical diagram shows the relationships between different AutoCAD objects.

4. To go to online help for Block reference, click on the BlockReference object. (This takes you to the online help you accessed through the Object Browser, as shown in figure 25.6.)

Now you know how to access help information for Automation objects in a couple of ways--from the Object Browser as well as from the AutoCAD online help file. This knowledge will be useful when you complete the next exercise, which does a simple customization of AutoCAD.

Using Automation with AutoCAD

This section shows how to use Automation to write simple, yet powerful utilities to customize AutoCAD. You can use Automation objects to perform most operations that you would perform interactively. Of course, no one-to-one correspondence exists between the two approaches.

The preceding exercise showed you how to use Visual Basic 5.0 to connect to AutoCAD. The next exercise shows you, step by step, how to create a Visual Basic macro, using AutoCAD VBA to set up top, front, isometric, and right views in paper space.

Setting Up Four Standard Viewports in Paper Space

In this exercise, after connecting to AutoCAD from VBA, you add a torus (donut) object, and then create the standard views. Finally, you zoom to fit the torus in each of the views. To be able to do this exercise, you must have AutoCAD VBA installed on your machine. Please refer to your AutoCAD Installation Guide for information about installing the AutoCAD VBA Preview.

CREATING A MACRO TO SET UP VIEWPORTS IN PAPER SPACE

1. Start AutoCAD, open the VBA pull-down menu and then choose Show VBA IDE. This starts AutoCAD VBA (Microsoft Visual Basic for Applications).

2. From the Insert menu, choose UserForm. The screen should look similar to figure 25.5.

3. If the toolbox does not appear, go to the View menu and choose the ToolBox command.

4. From the toolbox, click on the command button, and then click once on the form to display the command button.

5. Repeat step 4 five more times, creating a total of six command buttons on the form. Place them so that they do not overlap (see fig. 25.9).

Figure 25.9 VBA Editor with the six command buttons on the form.

6. Click once on each button, and set its properties in the properties sheet as follows:


NOTE: To change a property, double-click on the property name. This action selects the property and highlights its current value.

For CommandButton1, set the following properties:

Height: 24

Left: 18

Top: 12

Width: 60

Caption: Connect

Name: cmdConnect

For CommandButton2, set the following properties:

Height: 24

Left: 18

Top: 48

Width: 60

Caption: Add Torus

Name: cmdAdd

For CommandButton3, set the following properties:

Height: 24

Left: 18

Top: 84

Width: 60

Caption: End

Name: cmdQuit

For CommandButton4, set the following properties:

Height: 24

Left: 108

Top: 12

Width: 60

Caption: Create Views

Name: cmdViews

For CommandButton5, set the following properties:

Height: 24

Left: 108

Top: 48

Width: 60

Caption: Help

Name: cmdHelp

For CommandButton6, set the following properties:

Height: 24

Left: 108

Top: 84

Width: 60

Caption: Cancel

Name: cmdCancel

7. Select the form by clicking anywhere on an open spot on the form. Set its properties in the properties sheet as follows:

Caption: Standard View Creation Utility

8. From the File pull-down menu, choose Save. The Save VBA Project As dialog box is displayed. Type the name view.dvb and click on the OK button. (Save intermittently so that you don't lose your work.)


Now that you have laid out the buttons on the form, add the code that is executed when the user presses each button.

9. Double-click on the Connect button and add the following lines of code between the Private Sub and End Sub statements:

On Error Resume Next
Set acad = GetObject(, "AutoCAD.Application")
If Err Then
     Err.Clear
      Set acad = CreateObject("AutoCAD.Application")
      If Err Then
             MsgBox "Error in connecting to AutoCAD"
          Exit Sub
      End If
End If
acad.Visible = True
Set mspace = doc.ModelSpace
cmdQuit.Enabled = True
cmdAdd.Enabled = True
cmdViews.Enabled = True

10. From the View pull-down menu, choose Object to switch to the form. Double-click on the Add Torus button, and add the following lines of code between the Private Sub and End Sub statements:

Dim My_Torus As Object
Dim Center(1 To 3) As Double
Dim EndPoint(1 To 3) As Double
Dim TorusRadius As Double
Dim TubeRadius As Double
Center(1) = 2#
Center(2) = 2#
Center(3) = 0#
TorusRadius = 0.5
TubeRadius = 0.125
Set doc = acad.ActiveDocument
Set mspace = doc.ModelSpace
Set My_Torus = mspace.AddTorus(Center, TorusRadius, TubeRadius)
My_Torus.Update

11. Open the View pull-down menu and choose Object to switch to the form. Double-click on the Create Views button, and add the following lines of code between the Private Sub and End Sub statements:

Dim Center(0 To 2) As Double
Dim Origin(0 To 2) As Double
Dim Top As Object
Dim Front As Object
Dim Iso As Object
Dim Right As Object
Dim PSpace As Object
Dim topDir(0 To 2) As Double
Dim frontDir(0 To 2) As Double
Dim rightDir(0 To 2) As Double
Dim isoDir(0 To 2) As Double
Set PSpace = doc.PaperSpace
Origin(0) = 0#
Origin(0) = 0#
Origin(0) = 0#
doc.ActiveSpace = 0
Center(0) = 2.5
Center(1) = 7.5
Center(2) = 0#
Set Top = PSpace.AddPViewport(Center, 5, 5)     `Add the top ¬viewport 
Center(0) = 2.5
Center(1) = 2.5
Set Front = PSpace.AddPViewport(Center, 5, 5)  `Add the front ¬viewport
Center(0) = 7.5
Center(1) = 2.5
Set Right = PSpace.AddPViewport(Center, 5, 5) `Add the right ¬viewport
Center(0) = 7.5
Center(1) = 7.5
Set Iso = PSpace.AddPViewport(Center, 5, 5) `Add the iso viewport
frontDir(0) = 0            `Set the view direction in the front view
frontDir(1) = 1
frontDir(2) = 0
rightDir(0) = 1            `Set the view direction in the right view
rightDir(1) = 0
rightDir(2) = 0
isoDir(0) = 1              `Set the view direction in the iso view
isoDir(1) = 1
isoDir(2) = 1
Front.Direction = frontDir     `Assign the direction values 
Right.Direction = rightDir
Iso.Direction = isoDir
Top.Display (acOn)          `Turn the viewports on
Front.Display (acOn)
Iso.Display (acOn)
Right.Display (acOn)
doc.mspace = False     `Equivalent to AutoCAD pspace command 
doc.ActivePViewport.ZoomExtents     `Zoom extents
doc.mspace = True     `Equivalent to AutoCAD mspace command 
Set doc.ActivePViewport = Iso          `Make the iso view active
Iso.ZoomExtents                    `Zoom extents in iso view
Set doc.ActivePViewport = Right     `Make the right view active
Right.ZoomExtents               `Zoom extents in right view
Set doc.ActivePViewport = Front     `Make the front view active
Front.ZoomExtents               `Zoom extents in front view
Set doc.ActivePViewport = Top     `Make the top view active
Top.ZoomExtents               `Zoom extents in top view
doc.Regen (1)               `Do a regen in all viewports

12. From the View pull-down menu, choose Object to switch to the form. Double-click on the End button and add the following line of code between the Private Sub and End Sub statements:

End

13. From the View pull-down menu, choose Object to switch to the form. Double-click on the Cancel button and add the following line of code between the Private Sub and End Sub statements:

End

14. From the View pull-down menu, choose Object to switch to the form. Double-click on the Help button, and add the following line of code between the Private Sub and End Sub statements:

MsgBox (" This is a dummy help")

15. In the left list box at the top of the code window, select the (General) section. Add the following lines of code in the (Declarations) section:

Option Explicit
Public acad As Object
Public doc As Object
Public mspace As Object

16. Now that you have completed writing the code, save the project.

17. To execute the utility, open the Run pull-down menu and choose Run Sub/UserForm (see fig. 25.10).

Figure 25.10 The Run Sub/UserForm entry in the Run menu.

18. Click on the Connect button, and then click on Add Torus and Create Views, respectively. Connect sets up the link to AutoCAD (as explained for the first exercise).

Add Torus creates a three-dimensional torus object. The line Set doc = acad.ActiveDocument stores the ActiveDocument object (current drawing) in the doc variable. The next line, Set mspace = doc.ModelSpace, obtains the ModelSpace collection object and stores it in the mspace variable. ModelSpace is usually where AutoCAD adds all the graphical entities, unless you are creating blocks or paper space objects. The next line, Set My_Torus = mspace.AddTorus(Center, TorusRadius, TubeRadius), actually adds the torus. My_Torus.Update updates the AutoCAD screen to display the torus.

Create views follows the AutoCAD sequence of creating paper space viewports. First you obtain the paper space collection object and store it in the Pspace variable. The line doc.ActiveSpace = 0 is equivalent to setting Tilemode to 0 in AutoCAD. Then you add each of the four viewports. But you are not finished until you have set the x, y, and z values for the view direction in the viewports. Then you turn on each viewport by using the acOn constant for each viewport. The line doc.mspace = False is equivalent to typing Pspace in the AutoCAD command line. The remaining lines in the CreateViews routine perform a zoom extent in each viewport. The line doc.Regen (1) is used to regenerate in all the viewports. To regenerate in a single viewport, use doc.Regen(0).


TIP: Instead of remembering whether 1 or 0 does a regen in all viewports, use the mnemonic constants. To look them up in the Automation help file, bring up the object model and then, on the top menu, click on Constants.

Running a Macro in AutoCAD VBA

You can run this next exercise as a macro in AutoCAD VBA. Although the full benefits of Macros include record and playback capability (which is not available in AutoCAD), you can run the macro from the command line, or even put it in an AutoCAD menu by following these steps:

RUNNING A MACRO

1. Start AutoCAD, open the VBA pull-down menu, and choose Show VBA IDE. This starts AutoCAD VBA (Microsoft Visual Basic for Applications).

2. Open the Insert pull-down menu and then choose Module. Module1 is displayed in the project window and the code window is now empty.

Double-click on Module in the project window; the code window appears.

3. Enter the following lines in the code window (see fig. 25.11):

Sub My_Macro()
     Load UserForm1
     UserForm1.Show
End Sub

The first line, Load UserForm1, loads the form with the buttons. The line UserForm1.Show displays the form.

Figure 25.11 VBA window after step 3.

4. To run the macro, switch back to your AutoCAD session and type VBARUN (or open the VBA pull-down menu and choose Run Macro).

5. In the Macros dialog box, select Module1 from the Macro Scope list. In the second drop-down list, select MyMacro and then choose Run. The form you created in step 4 of this exercise appears again.

This exercise showed you how to automate tasks in AutoCAD by using VBA. Typically, however, you might use several products to perform various tasks. The next exercise shows you how to use Automation to automate these cross-application tasks. This is where the power of Automation lies, and is what sets it apart from AutoLISP.

Using Automation with Other Applications

You can use the VBA included with Office 97 or a variety of other products, including AutoCAD, to create cross-application programs by using objects from different applications. The following exercise takes you through the steps of creating one such application.

Creating an Application that Links AutoCAD, Microsoft Excel, and Microsoft Word

This exercise shows you how to open a drawing file, tabulate the count of various blocks in MS Excel, and then prepare a memo in MS Word--all in one simple application, using Excel VBA. Note that this exercise works with Excel 7.0, not Office 97 Excel or Excel 5.0. The names of objects supported in each Excel version have changed slightly and some modification in the given code may be required to run on Excel 5 or Office 97 Excel. Figure 25.12 shows the memo that your application creates by using objects from Word, Excel, and AutoCAD.

Figure 25.12 This Word document is based on AutoCAD drawing data tabulated in an Excel chart.

LINKING AUTOCAD, EXCEL, AND WORD

1. Open Microsoft Excel and, from the Insert menu, choose Macro, Module.

2. On the module sheet, add the following code for counting the AutoCAD blocks and tabulating them into the Excel worksheet. (You can also cut and paste the code from the file ew.xls supplied on the CD that accompanies this book.)

Public acad As Object
Public excelSheet As Object
Sub CountBlocks()
Dim objMspace As Object
Dim objElement As Object
Dim objExcel As Object
Dim objDoc As Object
Dim intI As Integer
Dim strBlockName(1 To 1000) As String
Dim intNumBlockName(1 To 1000) As Integer
Dim intTotalNumOfBlocks As Integer
Set objExcel = GetObject(, "Excel.Application")
Set objExcelSheet = objExcel.ActiveWorkbook.Sheets("Sheet1")
Worksheets("Sheet1").Activate
On Error Resume Next
Set objAcad = GetObject(, "AutoCAD.Application")
If Err <> 0 Then
            `Set objAcad = CreateObject("AutoCAD.Application")
Exit Sub
End If
    objAcad.Visible = True
    Set objDoc = objAcad.ActiveDocument
               If Right(ActiveWorkbook.Path, 1) = "\" Then
        DwgName = ActiveWorkbook.Path & "ew.dwg"
    Else
        DwgName = ActiveWorkbook.Path & "\ew.dwg"
    End If
    Set objDoc = objAcad.ActiveDocument
    If objDoc.FullName <> DwgName Then
        objDoc.Open DwgName
    End If         Set objMspace = objDoc.ModelSpace
    objExcelSheet.Range(Cells(1, 1), Cells(100, 12)).Clear
    intI = 1
    For Each objElement In objDoc.Blocks
        With objElement
            If (.Name <> "*MODEL_SPACE" And .Name <> "*PAPER_SPACE")              ¬Then
objExcelSheet.Cells(intI, 1) = objElement.Name
strBlockName(intI) = objElement.Name
 intI = intI + 1
End If
End With
Next
    intI = intI - 1
    intTotalNumOfBlocks = intI
    For intI = 1 To intTotalNumOfBlocks
        intNumBlockName(intI) = 0
    Next
   objExcelSheet.Range(Cells(1, 1), Cells(intI, 1)).Font.Bold = True
For Each objElement In objMspace
With objElement
                Found = False
                If StrComp(objElement.entityName, 
                ¬"AcDbBlockReference", 1) = 0 Then
                    For intI = 1 To intTotalNumOfBlocks
                        If Not Found Then
                            If StrComp(.Name, strBlockName(intI), 1)                              ¬= 0 Then
                                intNumBlockName(intI) =                                  ¬intNumBlockName(intI) + 1
                                Found = True
                            End If
                        End If
                    Next
                End If
            End With
            Set objElement = Nothing
    Next objElement
    For intI = 1 To intTotalNumOfBlocks
        objExcelSheet.Cells(intI, 2) = intNumBlockName(intI)
    Next
    CreateChart (intTotalNumOfBlocks)
    Auto_Wait
    MakeMemos
End Sub

3. Add the following subroutine to create an Excel chart based on the count of the AutoCAD blocks. You can customize your chart by using Excel objects and constants. For this subroutine to work, you must have MS Excel 7.0 installed on your system.

Private Sub CreateChart(NumberOfBlocks As Integer)
Dim ChartRange As Object
Static NewChart As Object
Set ChartRange = ActiveSheet.Range(Cells(1, 1), _
    Cells(NumberOfBlocks, 2))
ChartRange.Select
Set NewChart = Charts.Add
NewChart.Activate
With NewChart
        .Type = xl3DColumn
        .SubType = xlNormal
        .CopyPicture xlScreen
End With
End Sub


In the preceding routine, you have set the range of input for the Excel chart, added a chart to the Excel Charts collection and made it active. For the new chart object, you have set the type of chart that you want created.

4. Next, you write the code for an auto_wait subroutine. This routine adds an arbitrary wait of four seconds to give Microsoft Excel time to finish creating the chart object before Excel starts the Microsoft Word application.

Private Sub Auto_Wait()
        Dim NewHour As Double
        Dim NewMinute As Double
        Dim NewSecond As Double
        Dim WaitTime As Date
        NewHour = Hour(Now())
        NewMinute = Minute(Now())
        NewSecond = Second(Now()) + 4
        WaitTime = TimeSerial(NewHour, NewMinute, NewSecond)
        Application.Wait WaitTime 
End Sub

5. Now, write the code that starts Microsoft Word and inserts the chart you created in Excel into the Word document. You can include additional text information, where appropriate, to complete your memo. For this subroutine to work, you must have MS Word 6.0 installed on your system.

Private Sub MakeMemos()
    Dim Word As Object
    Set Word = CreateObject("Word.Basic")
    With Word
        .FileNewDefault
        .Insert "M E M O"
        .InsertPara
        .InsertPara
        .Insert "Date:" & Chr(9) & Format(Date, "mmm d, yyyy")
        .InsertPara
        .Insert "To: <Insert Name Here>"
        .InsertPara
        .Insert "From: <Your Name>"
        .InsertPara
        .Insert "Title "
        Word.EditPaste
        .InsertPara  `.Insert Message
        .InsertPara 
        .InsertPara
        .Insert "You can insert any text here as you like. "
        .InsertPara
        .Insert "Enter different text on each line...."
        .StartOfDocument
        .EndOfLine 1
        .Bold
        .CenterPara
        .FileSaveAs "C:\Demo.Doc"
        .DocClose
 End With
 Set Word = Nothing
Application.StatusBar = ""
MsgBox "The memo has been created and saved.", vbInformation
Set excelSheet = Nothing
End Sub


The preceding code starts Word.Basic application, opens a default document, adds some formatting information, and pastes the chart you created in Excel before saving the document.
Now you are ready to run this exercise.

6. From the Tools menu, choose Macro, and then select Count_Blocks (see fig. 25.13).

Figure 25.13 Microsoft Excel sheet shows the Macro entry under the Tools menu.

7. Click on Run, allowing time for AutoCAD to open and create a chart and Word document. This step may take some time to complete.

8. The Word document is stored as C:\demo.doc. You can change the path in the MakeMemos macro, if necessary.

Notice that you first connect to the running instance of the Excel application by using the GetObject function. The next statements activate Sheet1 on Excel, making it the current sheet, where the count for the blocks is written. Then you cycle through the AutoCAD database, identifying each different block and storing the information in the strBlockName variable, as well as writing it on the Excel sheet. Next, you loop through the database again, and add the count for each type of block in the intNumBlockName variable.

The CreateChart subroutine creates the chart by selecting the appropriate range. The MakeMemo subroutine starts the Word application and creates the Word document. You can customize this utility for your particular needs.

Summary

ActiveX Automation is a new feature in AutoCAD Release 14 that enables you to customize AutoCAD and create powerful integrated applications. The power of the Automation feature becomes clearly evident when used to integrate automation-compliant applications, such as Microsoft Word, Excel, and Access, with AutoCAD, something that AutoLISP is not well suited for. While AutoLISP is a powerful customization tool for AutoCAD, the Graphical User Interface (GUI) tools available in Visual Basic 5.0 are clearly superior to AutoLISP Dialog Control Language (DCL) and can be used easily to develop well-integrated Visual Basic applications.

In this chapter, you learned how to customize AutoCAD. You learned how to program with the new AutoCAD VBA. The last exercise showed you how to do cross-application macro programming using Excel, Word, and AutoCAD. Knowledge of these new tools will enable you to produce applications that maximize your productivity and enable you to automate tasks.


Previous chapterNext chapterContents

© Copyright, Macmillan Computer Publishing. All rights reserved.